<template>
  <div :device="device" class="dev-container">
    <div class="dev-header">
      <div class="dev-icon-wrapper card-icon">
        <svg-icon icon-class="x-ray" class-name="dev-icon" />
      </div>
      <div class="dev-info">
        <div class="dev-info-name"> {{ device.name }} </div>
      </div>
      <div style="float:right;margin:10px;">
        <el-button type="success" size="large" @click="dialogShowTableVisible = true"> 查看相关表格 </el-button>
        <el-button type="success" size="large" @click="saveSet"> 保存设置 </el-button>
      </div>
    </div>

    <div class="grid">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>条件</span>
          <div style="float:right;">
            <el-select v-model="device.value.auto" style="width:120px;margin-right:10px;" placeholder="请选择">
              <el-option v-for="item in AutoOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button style="float: right; padding: 3px 0" type="text" @click="dialogConditionVisible=true">选择条件</el-button>
          </div>
        </div>
        <el-form ref="form" label-width="100px" label-position="left">
          <el-form-item label="放射源">
            <el-select v-model="device.value.condition.RadiativeResource" style="width:120px;margin-right:10px;" placeholder="请选择">
              <el-option v-for="item in RadiativeResourceOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="衰减器组合">
            <el-checkbox-group v-if="device.value.auto" v-model="device.value.condition.Attenuator" disabled>
              <el-checkbox :label="1" />
              <el-checkbox :label="2" />
              <el-checkbox :label="3" />
              <el-checkbox :label="4" />
            </el-checkbox-group>
            <el-checkbox-group v-else v-model="device.value.condition.Attenuator">
              <el-checkbox :label="1" />
              <el-checkbox :label="2" />
              <el-checkbox :label="3" />
              <el-checkbox :label="4" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="距离(m)">
            <div class="row">
              <el-input v-if="device.value.auto" v-model="device.value.condition.Distance" disabled @input="getResult" />
              <el-input v-else v-model="device.value.condition.Distance" @input="getResult" />
            </div>
          </el-form-item>
          <el-form-item label="照射时长(s)">
            <el-input v-if="device.value.auto" v-model="device.value.condition.Time" disabled @input="getResult" />
            <el-input v-else v-model="device.value.condition.Time" @input="getResult" />
          </el-form-item>
          <el-form-item label="Nc/校准因子">
            <el-input v-model="device.value.condition.Nc" @input="getResult" />
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>结果</span>
          <div style="float:right;">
            <el-button style="float: right; padding: 3px 0" type="text" @click="dialogUnitVisible=true">修改单位</el-button>
          </div>
        </div>
        <el-form ref="form" label-width="180px" label-position="left">
          <el-form-item :label="'空气比释动能率(' + device.value.result.Kd_unit +'/'+ device.value.result.time+ ')'">
            <!-- <el-input v-model="device.value.result.Kd_rate" /> -->
            <el-input-number v-model="device.value.result.Kd_rate" controls-position="right" :min="-999999999" :max="999999999" :precision="3" />
          </el-form-item>
          <el-form-item :label="'空气比释动能(' + device.value.result.Kd_unit + ')'">
            <!-- <el-input v-model="device.value.result.Kd" /> -->
            <el-input-number v-model="device.value.result.Kd" controls-position="right" :min="-999999999" :max="999999999" :precision="3" />
          </el-form-item>
          <el-form-item :label="'周围剂量当量率(' + device.value.result.Hd_unit +'/'+ device.value.result.time+ ')'">
            <!-- <el-input v-model="device.value.result.Hd_rate" /> -->
            <el-input-number v-model="device.value.result.Hd_rate" controls-position="right" :min="-999999999" :max="999999999" :precision="3" />
          </el-form-item>
          <el-form-item :label="'周围剂量当量(' + device.value.result.Hd_unit + ')'">
            <!-- <el-input v-model="device.value.result.Hd" /> -->
            <el-input-number v-model="device.value.result.Hd" controls-position="right" :min="-999999999" :max="999999999" :precision="3" />
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-dialog title="修改单位" :visible.sync="dialogUnitVisible">
      <el-form ref="form" label-width="180px" label-position="left">
        <el-form-item label="时间">
          <el-select v-model="device.value.result.time" placeholder="请选择">
            <el-option v-for="item in TimeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogUnitVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUnitDialogSave">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择条件" :visible.sync="dialogConditionVisible">
      <el-table
        ref="signalTable"
        :data="device.value.tableDataAirKermaCondition"
        style="width: 100%"
        highlight-current-row
        @current-change="handleCurrentChangeCondition"
      >
        <el-table-column prop="TubeVoltage" label="管电压(kV)" />
        <el-table-column prop="Attenuator" label="衰减片" />
        <el-table-column prop="TubeCurrent" label="管电流(mA)" />
        <el-table-column prop="Distance" label="距离(m)" />
        <el-table-column prop="Nc" label="修正因子/Nc" />
        <el-table-column prop="Time" label="照射时间" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogConditionVisible=false">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirmCondition">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="相关计算表格" :visible.sync="dialogShowTableVisible" width="80%">
      <div class="grid">
        <el-card>
          <div slot="header" class="clearfix">
            <span>γ空气比释动能率计算-Co60</span>
          </div>
          <el-table
            :data="device.value.tableDataAirKermaCo60"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column prop="RadiativeResource" label="放射源" />
            <el-table-column prop="Attenuator" label="衰减片组合" />
            <el-table-column prop="K_1" label="K_1" />
            <el-table-column prop="T0" label="测定标准值时的日期" />
            <el-table-column prop="N1" label="N1" />
            <el-table-column prop="N2" label="N2" />
            <el-table-column prop="N3" label="N3" />
            <el-table-column prop="N4" label="N4" />
          </el-table>
        </el-card>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>γ空气比释动能率计算-Cs137</span>
          </div>
          <el-table
            :data="device.value.tableDataAirKermaCs137"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column prop="RadiativeResource" label="放射源" />
            <el-table-column prop="Attenuator" label="衰减片组合" />
            <el-table-column prop="K_1" label="K_1" />
            <el-table-column prop="T0" label="测定标准值时的日期" />
            <el-table-column prop="N1" label="N1" />
            <el-table-column prop="N2" label="N2" />
            <el-table-column prop="N3" label="N3" />
            <el-table-column prop="N4" label="N4" />
          </el-table>
          <!-- <upload-excel-component :on-success="handleSuccessExcelAirKermaCs137" :before-upload="beforeUploadExcel" /> -->
        </el-card>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>γ空气比释动能率计算-Am241</span>
          </div>
          <el-table
            :data="device.value.tableDataAirKermaAm241"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column prop="RadiativeResource" label="放射源" />
            <el-table-column prop="Attenuator" label="衰减片组合" />
            <el-table-column prop="K_1" label="K_1" />
            <el-table-column prop="T0" label="测定标准值时的日期" />
            <el-table-column prop="N1" label="N1" />
            <el-table-column prop="N2" label="N2" />
            <el-table-column prop="N3" label="N3" />
            <el-table-column prop="N4" label="N4" />
          </el-table>
          <!-- <upload-excel-component :on-success="handleSuccessExcelAirKermaCs137" :before-upload="beforeUploadExcel" /> -->
        </el-card>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>周围剂量当量率表格</span>
          </div>
          <el-table :data="device.value.tableDataDose" stripe border style="width: 100%">
            <el-table-column prop="Radio" label="辐射质" />
            <el-table-column prop="Distance" label="照射距离/m" />
            <el-table-column prop="H_K_10" label="h_k(10)/Sv*Gy-1" />
          </el-table>
        </el-card>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShowTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogShowTableVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import { editDevice } from '@/api/device'
import moment from 'moment'

const TimeOptions = [{ label: 'h', value: 'h' }, { label: 'min', value: 'min' }, { label: 's', value: 's' }]

export default {
  name: 'CountX',
  components: { },
  filters: { },
  props: {
    id: {
      type: Number,
      default: 0
    },
    device: {
      type: Object,
      default: null
    },
    value: {
      type: Object,
      default: null
    },
    name: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // tableDataAirKermaCo60: [],
      // tableDataAirKermaCs137: [],
      // tableDataAirKermaCondition: [],
      // tableDataDose: [],

      currentRow: null,

      RadiativeResourceOptions: [{ label: 'Co60', value: 'Co60' }, { label: 'Cs137', value: 'Cs137' }, { label: 'Am241', value: 'Am241' }],
      AutoOptions: [{ label: '自动', value: true }, { label: '手动', value: false }],

      TimeOptions: TimeOptions,

      dialogUnitVisible: false,
      dialogConditionVisible: false,
      dialogShowTableVisible: false
    }
  },
  watch: {
    device: {
      deep: true,
      handler(val) {
        this.setDevice(val)
        this.getResult()
      }
    }
  },
  created() {
    console.log(this.device.name + '信息')
    console.log(this.device.value)
    this.condition = this.device.value.condition
    this.Kd_rate = this.device.value.Kd_rate
    this.Kd = this.device.value.Kd
    this.Hd_rate = this.device.value.Hd_rate
    this.Hd = this.device.value.Hd
  },
  methods: {
    setDevice(val) {
      this.device = val
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row)
    },
    saveSet() {
      editDevice(this.device).then(response => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: response.message
          })
        } else this.$message(response.message)
      })
    },
    handleSetTableAirKermaSelect(val) {
      this.device.value.tableAirKermaSelect = val
    },
    handleUnitDialogSave() {
      console.log('保存单位')
      this.dialogUnitVisible = false
      this.saveSet()
    },

    handleCurrentChangeCondition(row) {
      this.currentRow = row
      console.log(this.currentRow)
    },
    handleDialogConfirmCondition() {
      try {
        var condition = JSON.parse(JSON.stringify(this.currentRow))
        this.device.value.condition.TubeVoltage = condition.TubeVoltage
        this.device.value.condition.TubeCurrent = condition.TubeCurrent
        this.device.value.condition.Attenuator = condition.Attenuator
        this.device.value.condition.Distance = condition.Distance
        this.device.value.condition.Time = condition.Time
        this.device.value.condition.Nc = condition.Nc
        this.clearResult()
        this.getResult()
        this.dialogConditionVisible = false
      } catch (error) {
        console.log(error)
        this.$message({ type: 'error', message: error })
      }
    },
    datedifference(sDate1, sDate2) { // sDate1和sDate2是2006-12-18格式
      var dateSpan, iDays
      sDate1 = Date.parse(sDate1)
      sDate2 = Date.parse(sDate2)
      dateSpan = sDate2 - sDate1
      dateSpan = Math.abs(dateSpan)
      iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
      return iDays
    },
    clearResult() {
      this.deivce.value.reslut.Kd = 0
      this.deivce.value.reslut.Kd_rate = 0
      this.deivce.value.reslut.Hd = 0
      this.deivce.value.reslut.Hd_rate = 0
    },

    getResult() {
      try {
        var condition = this.device.value.condition
        var result = this.device.value.result
        var Attenuator = null // 衰减器组合
        var Nc = condition.Nc // 修正因子
        var T = 0 // 半衰期
        var k1 = 0 // 1米处标准值
        var N = 0

        var t0 = condition.t0 // 标准值测量时间
        var t = moment().format('YYYY-MM-DD')// 当前时间

        var d = condition.Distance // 距离
        var time = condition.Time // 照射时长

        var kd_rate = 0 // 空气比释动能率
        var kd = 0 // 空气比释动能

        var table = null
        // 选择表格进行查表计算
        if (condition.RadiativeResource === 'Co60') {
          table = this.device.value.tableDataAirKermaCo60
          T = 5.26 * 365.25
        }
        if (condition.RadiativeResource === 'Cs137') {
          table = this.device.value.tableDataAirKermaCs137
          T = 30.2 * 365.25
        }
        if (condition.RadiativeResource === 'Am241') {
          table = this.device.value.tableDataAirKermaAm241
          T = 432.2 * 365.25
        }
        if (table === null) {
          this.$message({ type: 'error', message: '[' + condition.RadiativeResource + ']->未查询到对应条件的表格' })
          return
        }
        console.log('table:')
        console.log(table)
        var item = null
        for (var i = 0; i < table.length; i++) {
          item = JSON.parse(JSON.stringify(table[i]))
          // 检查衰减片是否满足
          Attenuator = JSON.parse(JSON.stringify(condition.Attenuator)).sort()
          if (JSON.stringify(Attenuator) === item.Attenuator) {
            // 计算N
            var n_arr = [item.N1, item.N2, item.N3, item.N4]
            N = 0
            for (i = 1; i < n_arr.length; i++) {
              if (d >= i && d <= i + 1) {
                console.log('i:' + i)
                N = (n_arr[i] - n_arr[i - 1]) * d + n_arr[i] - (n_arr[i] - n_arr[i - 1]) * i
                break
              }
            }
            k1 = item.K_1
            t0 = item.T0
            break
          }
        }

        console.log('计算空气比释动能率:')
        console.log('Attenuator:', JSON.stringify(Attenuator))
        console.log('k1:' + k1)
        console.log('d:' + d)
        console.log('N:' + N)
        console.log('t:' + t)
        console.log('t0:' + t0)
        console.log('T:' + T)
        console.log('Nc:' + Nc)

        // var err_days = this.datedifference('2021-08-01', '2017-08-01')
        var t_t0 = this.datedifference(t, t0)
        console.log('t-t0:' + t_t0)
        // 计算空气比释动能率
        kd_rate = (k1 / (d * d)) * N * Math.pow(0.5, t_t0 / T) * Nc

        // 单位换算
        var time_scale = 0
        if (result.time === 'h') {
          kd_rate = kd_rate * 1
          time_scale = time / 3600
        }
        if (result.time === 'min') {
          kd_rate = kd_rate / 60
          time_scale = time / 60
        }
        if (result.time === 's') {
          kd_rate = kd_rate / 60 / 60
          time_scale = time * 1
        }

        kd_rate = kd_rate.toFixed(3)

        if (kd_rate >= 0 && kd_rate <= 1000) {
          result.Kd_rate = kd_rate
          result.Kd_unit = 'uGy'
          result.Hd_unit = 'uSv'
        } else if (kd_rate > 1000 && kd_rate <= 1000000) {
          kd_rate = kd_rate / 1000
          result.Kd_rate = kd_rate
          result.Kd_unit = 'mGy'
          result.Hd_unit = 'mSv'
        } else if (kd_rate > 1000000) {
          kd_rate = kd_rate / 1000 / 1000
          result.Kd_rate = kd_rate
          result.Kd_unit = 'Gy'
          result.Hd_unit = 'Sv'
        }
        console.log('计算空气比释动能:')
        console.log('kd_rate:' + kd_rate)
        console.log('time_scale:' + time_scale)
        // 默认是uGy/h
        kd = kd_rate * time_scale
        result.Kd = kd

        // 计算周围剂量当量率
        var hd_rate = 0
        var hd = 0
        var radio = null // 辐射质
        var tableDataDose = this.device.value.tableDataDose
        if (condition.RadiativeResource === 'Cs137') {
          radio = 'S-Cs'
        }
        if (condition.RadiativeResource === 'Co60') {
          radio = 'S-Co'
        }
        if (condition.RadiativeResource === 'Am241') {
          radio = 'S-Am'
        }
        // 查表获取周围剂量当量率-空气比释动能率转换因子
        for (i = 0; i < tableDataDose.length; i++) {
          item = JSON.parse(JSON.stringify(tableDataDose[i]))
          if (radio === item.Radio) {
            var distance = item.Distance.split('-')
            console.log(distance)
            if (d >= parseFloat(distance[0]) && d <= parseFloat(distance[1])) {
              var h_k_10 = item.H_K_10
              hd_rate = kd_rate * h_k_10
            } else {
              hd_rate = 0
            }
            break
          }
        }
        // 固定下小数，不然时间不对
        hd_rate = hd_rate.toFixed(3)
        // 周围剂量当量
        hd = hd_rate * time_scale
        result.Hd_rate = hd_rate
        result.Hd = hd
      } catch (error) {
        console.log(error)
        this.$message({ type: 'error', message: error })
      }
    }

  }
}
</script>

<style lang="scss" scoped>

.offline {
  -webkit-filter: grayscale(100%);
  -moz-filter: grayscale(100%);
  -ms-filter: grayscale(100%);
  -o-filter: grayscale(100%);
  filter: grayscale(100%);
  filter: gray;
}

.name {
  width: 80px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.45);
  font-size: 20px;
}

.success {
  color: rgba(0, 187, 0, 0.45);
  font-weight: bold;
  font-size: 20px;
}

.danger {
  color: rgba(255, 0, 0, 0.45);
  font-weight: bold;
  font-size: 20px;
}

.dev-container {
  margin: 10px;
  background: #fff;
  width: 100%;
  transition: 0.3s;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  border-radius: 10px;
  &:hover {
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
  }
}

.dev-header {
    background:#fff;
    height: 110px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    color: #666;
    border-color: rgba(0, 0, 0, .55);
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    border-bottom:1px solid #ccc;
    // &:hover {
    //   .dev-icon-wrapper {
    //     color: #fff;
    //   }

    //   .card-icon{
    //     background: #40c9c6;
    //   }
    // }
    .dev-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
      color: #40c9c6;
    }

    .dev-icon {
      float: left;
      font-size: 48px;
    }

    .dev-info {
      float: left;
      font-weight: bold;
      margin: 26px;
      .dev-info-name {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 20px;
        margin-bottom: 12px;
      }
      .dev-info-position {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }
      .dev-online {
        line-height: 18px;
        color: rgba(0, 255, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }
      .dev-offline {
        line-height: 18px;
        color: rgba(255, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }
    }
}

.row {
  width: 100%;
  display:flex;
  display:-webkit-flex;/*Safari*/
  justify-content:space-around;/*水平排布方式*/
  align-items:center;/*垂直对齐方式*/
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
}
.grid-condition {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-row-gap: 10px;
  grid-column-gap: 10px;
}

.box-card{
  margin: 0px;
}
</style>
